package com.jing.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.jing.common.core.utils.StringUtils;
import com.jing.product.domain.po.ProductAttribute;
import com.jing.product.domain.po.ProductAttributeCategory;
import com.jing.product.domain.vo.ProductAttrRelVO;
import com.jing.product.domain.vo.ProductAttributeCategoryVO;
import com.jing.product.domain.vo.ProductCategoryVO;
import com.jing.product.mapper.ProductAttributeCategoryMapper;
import com.jing.product.service.ProductAttributeCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author：HaoYunde
 * @Package：com.jing.product.service.impl
 * @Project：Jing
 * @name：ProductAttributeCategoryServiceImpl
 * @Date：2024/5/24 11:18
 */
@Service
public class ProductAttributeCategoryServiceImpl  implements ProductAttributeCategoryService {
    @Autowired
    private ProductAttributeCategoryMapper mapper;


    @Override
    public List<ProductAttributeCategoryVO> page( ) {
        return mapper.page();
    }

    @Override
    public void delect(Integer id) {
        int flag=mapper.delect(id);
        if(flag==0){
            throw new RuntimeException("删除失败");
        }
    }

    @Override
    public void add(ProductAttributeCategory productAttributeCategory) {
        int flag=mapper.add(productAttributeCategory);
        if(flag==0){
            throw new RuntimeException("添加成功");
        }
    }

    @Override
    public void update(ProductAttributeCategory productAttributeCategory) {
        int flag=mapper.update(productAttributeCategory);
        if(flag==0){
            throw new RuntimeException("修改失败");
        }
    }

    @Override
    public List<ProductAttributeCategoryVO> findAllproductAttributeCategory() {
        return mapper.findAllproductAttributeCategory();
    }

    @Override
    public List<ProductCategoryVO> getValueByid(Integer id, Integer type) {
        List<ProductAttribute> list=mapper.getValueByid(id,type);
        if(CollectionUtils.isEmpty(list)){
            throw new RuntimeException("没有数据,请确定参数是否正确");
        }
        return changCategoryValue(list);
    }


    private List<ProductCategoryVO> changCategoryValue(List<ProductAttribute> list) {
        //创建返回的结果集
        ArrayList<ProductCategoryVO> result = new ArrayList<>();
        for (ProductAttribute productAttribute : list) {
            ProductCategoryVO productCategoryVO = new ProductCategoryVO();
            productCategoryVO.setId(productAttribute.getId());
            productCategoryVO.setCategoryName(productAttribute.getName());
            if(StringUtils.isNotEmpty(productAttribute.getInputList())){
                String[] split = productAttribute.getInputList().split(",");
                //数组转换集合
                List<String> collect = Arrays.stream(split)
                        .collect(Collectors.toList());
                productCategoryVO.setValueList(collect);

                ArrayList<ProductAttrRelVO> productAttrRelVOS = new ArrayList<>();
                for (String attrValue : collect) {
                    ProductAttrRelVO productAttrRelVO = new ProductAttrRelVO();
                    productAttrRelVO.setAttrName(attrValue);
                    productAttrRelVO.setCid(productCategoryVO.getId());
                    productAttrRelVOS.add(productAttrRelVO);
                }
                productCategoryVO.setObjectList(productAttrRelVOS);
            }
            result.add(productCategoryVO);
        }
        return result;
    }

    @Override
    public List<Map<Integer, String>> saveProductAttributeCategory(List<ProductAttrRelVO> list) {
            Map<String, List<ProductAttrRelVO>> groupedByCid = list.stream()
                    .collect(Collectors.groupingBy(
                            map -> String.valueOf(map.getCid()), // 分组键
                            Collectors.toList() // 收集器
                    ));
            //使用笛卡尔积

            // 按cid分组
            Map<Integer, List<ProductAttrRelVO>> categoryById = list.stream()
                    .collect(Collectors.groupingBy(ProductAttrRelVO::getCid));

            // 获取所有唯一的cid
            Set<Integer> uniqueCids = new HashSet<>(categoryById.keySet());

            // 生成所有可能的组合
            List<Map<Integer, String>> combinations = generateCombinations(categoryById, uniqueCids);

            // 打印结果

            for (Map<Integer, String> combination : combinations) {
                System.out.println(JSON.toJSON(combination));
            }
            return combinations;
    }

    @Override
    public List<ProductCategoryVO> getValueByid2(Integer id, Integer type) {
        List<ProductAttribute> list=mapper.getValueByid2(id,type);
        if(CollectionUtils.isEmpty(list)){
            throw new RuntimeException("没有数据,请确定参数是否正确");
        }
        return changCategoryValue(list);
    }

    private static List<Map<Integer, String>> generateCombinations(Map<Integer, List<ProductAttrRelVO>> categoryById, Set<Integer> uniqueCids) {
        List<Map<Integer, String>> result = new ArrayList<>();

        // 对每个唯一的cid，准备其attrName的列表
        List<List<String>> attrLists = uniqueCids.stream()
                .map(cid -> categoryById.getOrDefault(cid, Collections.emptyList()).stream()
                        .map(ProductAttrRelVO::getAttrName)
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());

        // 使用递归或迭代生成组合
        backtrack(attrLists, 0, new HashMap<>(), result);

        return result;
    }

    private static void backtrack(List<List<String>> attrLists, int index, Map<Integer, String> currentCombination, List<Map<Integer, String>> result) {
        if (index == attrLists.size()) {
            // 所有列表都已遍历，添加当前组合到结果中
            result.add(new HashMap<>(currentCombination));
        } else {
            List<String> currentList = attrLists.get(index);
            for (String attr : currentList) {
                // 添加当前attr到组合中，并处理下一个列表
                currentCombination.put(index + 1, attr); // 假设cid从1开始
                backtrack(attrLists, index + 1, currentCombination, result);
                // 回溯：移除当前attr，以便尝试下一个
                currentCombination.remove(index + 1);
            }
        }
    }

}
